package com.chat.common.user.service.impl;

import com.chat.common.common.constant.RedisKey;
import com.chat.common.common.utils.JwtUtils;
import com.chat.common.common.utils.RedisUtils;
import com.chat.common.user.service.LoginService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Description: 登录相关处理类
 * Author: lin
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    //token过期时间
    private static final Integer TOKEN_EXPIRE_DAYS = 5;
    //token续期时间
    private static final Integer TOKEN_RENEWAL_DAYS = 2;
    @Resource
    private JwtUtils jwtUtils;

    /**
     * 校验token是不是有效
     *
     */
    @Override
    public boolean verify(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return false;
        }
        String key = RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
        String realToken = RedisUtils.getStr(key);
        return Objects.equals(token, realToken);//有可能token失效了，需要校验是不是和最新token一致
    }

    /**
     * 刷新token有效期
     *
     */
    @Async
    @Override
    public void renewalTokenIfNecessary(String token) {
        Long uid = getValidUid(token);
        String redisTokenKey = getRedisTokenKey(uid);
        //获取过期时间
        Long expireDays = RedisUtils.getExpire(redisTokenKey, TimeUnit.DAYS);
        if (expireDays==-2) {
            return;
        }
        if (expireDays < TOKEN_RENEWAL_DAYS) {
            RedisUtils.expire(redisTokenKey, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        }


    }

    /**
     * 登录成功，获取token
     *
     * @return 返回token
     */
    @Override
    public String login(Long uid) {
        String token = jwtUtils.createToken(uid);
        //将我们的token 缓存到redis中
        RedisUtils.set(getRedisTokenKey(uid),token,TOKEN_EXPIRE_DAYS,TimeUnit.DAYS);
        return token;
    }

    /**
     * 如果token有效，返回uid
     *
     */
    @Override
    public Long getValidUid(String token) {
        //检验token是否有效并且解密token 获取token对应的uid
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return null;
        }
        String oldToken = RedisUtils.getStr(getRedisTokenKey(uid));
        return Objects.equals(oldToken, token) ? uid : null;
    }

    /**
     * 根据用户的uid 拼接处用户存在redis的key
     */
    private String getRedisTokenKey(Long uid) {
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING,uid);
    }
}